package cn.com.Util;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.security.SecureRandom;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @ClassName ToolUtil
 * @Description
 * @Author wud
 * @Date 2020/11/3 19:49
 */
@Slf4j
public class ToolUtil {

    public static final Logger logger = LoggerFactory.getLogger(ToolUtil.class);

    public static final String FORMAT = "yyyy-MM-dd HH:mm:ss";

    public static final String FMT = "yyyyMMdd";

    public static final String DAY = "yyyy-MM-dd";

    public static final String MONTH = "yyyy-MM";

    /**
     * 日期校验
     */
    public static final String PREFIX = "^((19|20)[0-9][0-9]-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)$";

    /**
     * 时间校验，带空格
     */
    public static final String SUFFIX = "^ (([0-2][0-3])|([0-1][0-9])):[0-5][0-9]:[0-5][0-9]$";

    /**
     * 月份校验
     */
    public static final String MONTH_FORMAT = "^((19|20)[0-9][0-9])-(0[123456789]|1[012])$";

    /**
     * 判断字符串为空（null或者""）
     *
     * @param s
     * @return
     */
    public static boolean isEmpty(String s) {
        return s == null || s.length() == 0;
    }

    /**
     * 判断字符串不为空（null或者""）
     *
     * @param s
     * @return
     */
    public static boolean isNotEmpty(String s) {
        return !isEmpty(s);
    }

    /**
     * 判断List为空（null或者[]）
     *
     * @param list
     * @return
     */
    public static boolean isEmpty(List<?> list) {
        return list == null || list.isEmpty();
    }

    /**
     * 判断List不为空（null或者[]）
     *
     * @param list
     * @return
     */
    public static boolean isNotEmpty(List<?> list) {
        return !isEmpty(list);
    }

    /**
     * 日期校验
     *
     * @param date
     * @return
     */
    public static boolean verify(String date, String format) {
        if (isNotEmpty(format)) {
            switch (format) {
                case FORMAT:
                    return verify(date);
                case DAY:
                    return Pattern.matches(PREFIX, date);
                case MONTH:
                    return Pattern.matches(MONTH_FORMAT, date);
                default:
                    return false;
            }
        }
        return false;
    }

    /**
     * 日期校验
     *
     * @param date
     * @return
     */
    public static boolean verify(String date) {
        int length = 19;
        if (date.length() == length) {
            return Pattern.matches(PREFIX, date.substring(0, 10)) && Pattern.matches(SUFFIX, date.substring(10, length));
        }
        return false;
    }

    /**
     * date To Str
     *
     * @param date
     * @return
     */
    public static String dateToStr(Date date, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }

    public static Date strToDate(String str) {
        return strToDate(str, FORMAT);
    }

    public static Date strToDate(String str, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            logger.error("日期转换错误", e);
        }
        return date;
    }

    public static String getNowTimeByGMT8() {
        //查询当天的服务计划
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String now = formatter.format(new Date());
        return now;
    }

    /**
     * 获取几天前或者几天后的0点
     *
     * @param num
     * @return
     */
    public static String getNowAgoOrLaterTime(int num) {
        OffsetDateTime offsetDateTime = OffsetDateTime.now().withHour(0).withMinute(0).withSecond(0).plusDays(num);
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern(FORMAT);
        String format = pattern.format(offsetDateTime);
        return format;
    }

    /**
     * 获取几天前或者几天后的0点
     *
     * @param num
     * @return
     */
    public static String getNowAgoOrLaterTime(int num, String patternStr) {
        OffsetDateTime offsetDateTime = OffsetDateTime.now().plusDays(num);
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern(patternStr);
        String format = pattern.format(offsetDateTime);
        return format;
    }


    /**
     * List<T> 转 str,str
     *
     * @param list
     * @return
     */
    public static String getSplitStr(List<String> list) {
        String str = "";
        if (ToolUtil.isNotEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                if (i == list.size() - 1) {
                    str += list.get(i);
                } else {
                    str += list.get(i) + ",";
                }
            }
        }
        return str;
    }

    /**
     * 获取[,]截取的第一个字符
     *
     * @param str
     * @return
     */
    public static String getSplitFirst(String str) {
        return str != null ? str.split(",")[0] : null;
    }

    /**
     * 判断是否转Int类型
     *
     * @param str
     * @return
     */
    public static Integer parseStrToInt(String str) {
        return isNotEmpty(str) && str.equals("是") ? 1 : 0;
    }

    /**
     * 转Int类型
     *
     * @param str
     * @return
     */
    public static Integer parseIntger(String str) {
        return isNotEmpty(str) ? Integer.parseInt(str) : 0;
    }

    public static Map<String, Object> objectToMap(Object obj) {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            try {
                map.put(field.getName(), field.get(obj));
            } catch (IllegalAccessException e) {
                //e.printStackTrace();
            }
        }
        return map;
    }

    public static Map<String, Object> objectToMapFilterNull(Object obj) {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            try {
                if (field.get(obj) != null) {
                    map.put(field.getName(), field.get(obj));
                }
            } catch (IllegalAccessException e) {
                //e.printStackTrace();
            }
        }
        return map;
    }


    public static Integer nullZero(Integer num) {
        return num == null ? 0 : num;
    }

    public static Long nullZero(Long num) {
        return num == null ? 0L : num;
    }

    /**
     * 随机生成字母+数字字符串
     *
     * @return String
     */
    public static String randomCode(int i) {
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String charStr = String.valueOf(chars.charAt((int) (Math.random() * 52)));
        // 创建一个生产随机数的对象
        try {
            Random r = SecureRandom.getInstanceStrong();
            // 通过对象方法获取随机数
            String numStr = String.valueOf(r.nextInt(i));
            return charStr + numStr;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

}

